<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of pgsql
 *
 * @author n3621
 */

include "json.class.php";
class pgsql {
    private $host; 
    private $username; 
    private $password; 
    private $port; 
    private $dbname; 
    private $result;
    private $dbconnect;
    
    public function __construct() {
        $this->host = "localhost";
        $this->username="postgres";
        $this->password = "";
        $this->dbname = "trace";
        $this->connect();
    }
    
    private function connect() {
        $connect="host=".$this->host." port=5432 dbname=".$this->dbname." user=".$this->username; 
        if (!empty($this->password)) {
            $connect.=" password=".$this->password; 
        }

        $this->dbconnect=pg_connect ($connect); 
    }
    
    public function query($sql) {
        $this->result = pg_query($this->dbconnect, $sql);
        return $this->result;
    }
    
    public function fetch() {
		for($i=0, $cnt=$this->numrows(); $i<$cnt; $i++) {
	        $rtn[] = pg_fetch_array($this->result, $i, PGSQL_ASSOC);
		}
        return $rtn;
    }
    public function numrows() {
        $rtn = pg_numrows($this->result);
        return $rtn;
    }

	public function fetchJson() {
		$tmpArray	= $this->fetch();
		$objJson = new json();
		return "{\"data\" : " . $objJson->encode($tmpArray) . "}";
	}
}

?>